package cn.gson.crm.controller.pay;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.gson.crm.controller.BaseServlet;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.dao.StudentPayDao;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.po.StudentPayPo;

@WebServlet("/student/pay")
public class StudentPayServlet extends BaseServlet {

	/**
	 * 学生付款
	 */
	private static final long serialVersionUID = 1L;
	private StudentPayDao stuPayDao = new StudentPayDao();
	private StudentDao stuDao = new StudentDao();

	@Override
	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		StudentPayPo stuPayPo = stuPayDao.getPayRecord(id);
		Student student = stuDao.getStudentById("正常", "已分配", Integer.parseInt(id));
		request.setAttribute("stuPayPo", stuPayPo);
		request.setAttribute("student", student);
		// 通过id查找到学生相关信息
		forward("pay/pay_fee.jsp");
	}

	@Override
	protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String stuId = request.getParameter("stuId");
		String empId = request.getParameter("empId");
		String classType = request.getParameter("classType");
		String thisPay = request.getParameter("thisPay");
		String payWay = request.getParameter("payWay");
		String duePay = request.getParameter("duePay");
		StudentPayPo po = new StudentPayPo();
		po.setId(Integer.parseInt(stuId));
		po.setEmpId(Integer.parseInt(empId));
		po.setThisPay(Integer.parseInt(thisPay));
		StudentPayPo stuPayPo = stuPayDao.getPayRecord(stuId);
		//学员第一次缴费
		if (stuPayPo.getpId() == null) {
			po.setPayWay(payWay);
			po.setDuePay(Integer.parseInt(duePay));
			//根据学员缴费情况isAllPay给加状态,2未缴清，1为未缴清
			if(Integer.parseInt(duePay)==Integer.parseInt(thisPay)){
				po.setIs_allpay(2);
				stuDao.changePayStatus(po);
			}else{
				po.setIs_allpay(1);
				stuDao.changePayStatus(po);
			}
		} 
		//学员非第一次缴费
		else {
			po.setPayWay(stuPayPo.getPayWay());
			po.setDuePay(stuPayPo.getDuePay());
			//根据学员缴费情况isAllPay给加状态,2未缴清，1为未缴清
			if(stuPayPo.getNoPay()==Integer.parseInt(thisPay)){
				po.setIs_allpay(2);
				stuDao.changePayStatus(po);
			}else{
				po.setIs_allpay(1);
				stuDao.changePayStatus(po);
			}
		}

		if (stuPayDao.createPayRecord(po)) {
			request.getSession().setAttribute("id", stuId);
			redirect("student/haventpay");
		}else{
			request.setAttribute("erro", "缴费失败！请重试");
			forward("pay/pay_fee.jsp");
		}
		//如果学员未分班，classType为空，则在缴费时确定学员选择学制和学费
		if(classType!=null&&!classType.isEmpty()){
			po.setClassType(Integer.parseInt(classType));
			stuDao.addClassType(po);
		}
	}

}
